<template>
  <div class="home">
    <div class="home-container">
      <div class="home-menu">
        <div class="menu-header" style="display: flex;align-items: center;justify-content: center;flex-direction: column;">
          {{ shop.data.name }}
           <img :src="baseUrl+shop.data.avatar" class="shop-avatar" style="margin-top: 10px;font-weight: bold;"/> 
           <div class="team-info">
          
            <!-- {{ shop.name }} -->
          </div> 
        </div>
        <div class="menu-box" style="position: relative;">
          <div class="menu-list">
            <router-link tag="div" class="menu-item" to="/conversations" replace>
              <i class="iconfont icon-zaixiankefu"></i>
              <span v-if="unreadAmount + pendingConversationAmount" class="menu-unread">{{ unreadAmount +
                pendingConversationAmount}}</span>
            </router-link>

          </div>
          <button class="logout-btn" @click="logout">退出</button>
        </div>
      </div>
      <div class="home-main">
        <router-view />
      </div>
    </div>
  </div>
</template>

<script>
import RestApi from '../api/restapi'
import { baseUrl, webSocketUrl } from '../api/request'
import { io } from 'socket.io-client'
import { EventBus } from '../utils/eventBus'
export default {
  name: 'Home',
  data() {
    return {
      baseUrl:baseUrl,
      csteam: null,
      currentAgent: null,
      shop: null,
      unreadAmount: 0,
      pendingConversationAmount: 0,
      ws: null,
      reconnectTimer: null,
      reconnectCount: 0,
      maxReconnectCount: 5,
      reconnectInterval: 3000,
      heartbeatTimer: null,
      heartbeatInterval: 30000, // 30秒心跳
      onlineConfig: {
        visible: false,
        online: false
      }
    };
  },
  created() {
    this.shop = JSON.parse(localStorage.getItem('user'))
    console.log(this.shop);
    
    // this.currentAgent = this.globalData.currentAgent;
    // this.shop = RestApi.findShopById(this.currentAgent.id);

    // this.csteam = this.goEasy.im.csteam(this.currentAgent.id);

    if (this.goEasy.getConnectionStatus() === 'disconnected') {
      this.connectGoEasy();  //连接goeasy
    }
    this.initWebSocket();
    this.initialOnlineStatus();


    // 检查页面刷新时的路由跳转
    if (performance.navigation.type === performance.navigation.TYPE_RELOAD) {
      if (this.$route.path.includes('chat')) {
        console.log("我啊");

        this.$router.replace('/conversations');
      }
    }
  },
  beforeDestroy() {
    this.closeWebSocket();
  },
  methods: {
    connectGoEasy() {
      let currentAgent = this.currentAgent;

    },
    initWebSocket() {
      try {
        const token = localStorage.getItem('token');
        console.log("初始化WebSocket连接");

        // 将token添加到URL中
        const wsUrl = `${webSocketUrl}?token=${token}`;
        this.ws = new WebSocket(wsUrl);

        this.ws.onopen = () => {
          console.log('WebSocket connected');
          this.reconnectCount = 0;
          // 清除重连定时器
          if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
            this.reconnectTimer = null;
          }
          // 开始心跳检测
          this.startHeartbeat();
        };

        this.ws.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data);
            console.log('Received message:', data);

            if (data.content_type == 'addNotAccess') {
              EventBus.$emit('addNotAccess');
              return

             }
             if (data.content_type == 'deleteAccess') {
              EventBus.$emit('addNotAccess');
              return

            }
            if (data.content_type == 'deleteNotAccess') {
              EventBus.$emit('addNotAccess');
              return

             }
            // 如果是心跳响应，不需要处理
            if (data.type === 'pong') {
              console.log('Received heartbeat response');
              return;
            }

            // 通过事件总线发送消息给 Chat 组件
            EventBus.$emit('websocket-message', data);
          } catch (error) {
            console.error('Message parse error:', error);
          }
        };

        this.ws.onclose = (event) => {
          console.log('WebSocket closed, code:', event.code, 'reason:', event.reason);
          this.ws = null;
          this.stopHeartbeat();
          this.reconnect();
        };

        this.ws.onerror = (error) => {
          console.error('WebSocket error:', error);
          if (this.ws) {
            this.ws.close();
          }
        };

      } catch (error) {
        console.error('WebSocket init error:', error);
        this.reconnect();
      }
    },
    startHeartbeat() {
      this.stopHeartbeat();
      this.heartbeatTimer = setInterval(() => {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
          this.ws.send(JSON.stringify({ type: 'ping' }));
          console.log('Sent heartbeat ping');
        }
      }, this.heartbeatInterval);
    },
    stopHeartbeat() {
      if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer);
        this.heartbeatTimer = null;
      }
    },
    closeWebSocket() {
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = null;
      }
      this.stopHeartbeat();
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },
    reconnect() {
      if (this.reconnectCount >= this.maxReconnectCount) {
        console.log('Max reconnection attempts reached');
        return;
      }

      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer);
      }

      this.reconnectTimer = setTimeout(() => {
        console.log(`Reconnecting... Attempt ${this.reconnectCount + 1}/${this.maxReconnectCount}`);
        this.reconnectCount++;
        this.initWebSocket();
      }, this.reconnectInterval);
    },
    setUnreadAmount(content) {
      this.unreadAmount = content.unreadTotal;
    },
    setPendingConversationAmount(content) {
      this.pendingConversationAmount = content.conversations.length;
    },
    initialOnlineStatus() {

    },
    offline() {
      if (this.onlineConfig.online === false) {
        return
      }
      this.csteam.offline({
        onSuccess: () => {
          this.onlineConfig.online = false;
          console.log('已下线', this.currentAgent);
        },
        onFailed: (error) => {
          console.log('下线失败,error:', error);
          if (error.content === 'Please end your accepted conversations first') {
            alert('下线失败，请先结束已接入的会话！');
          }
        }
      })
    },
    online() {
      if (this.onlineConfig.online === true) {
        return
      }
      this.csteam.online({
        teamData: { name: this.shop.name, avatar: this.shop.avatar },
        agentData: { name: this.currentAgent.name, avatar: this.currentAgent.avatar },
        onSuccess: () => {
          this.onlineConfig.online = true;
          console.log('已上线', this.currentAgent);
        },
        onFailed: (error) => {
          console.log('上线失败,error:', error);
        }
      })
    },
    logout() {


      if (confirm('确认要退出登录吗？')) {
        try {
        this.closeWebSocket();
        this.ws.close();
        this.ws = null;
        } catch (error) {
          
        }
        
    
        
        localStorage.removeItem('token');
        this.$router.replace({ path: '/login' });
        EventBus.$emit('loginOut');

      }
    },
    closeOnlinePopup() {
      this.onlineConfig.visible = false;
    }
  },
};
</script>

<style scoped>
.logout-btn {
  position: absolute;
  position: absolute;
  bottom: 20px;
  width: 40px;
  height: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 6px;
  color: white;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);

}

@media screen and (max-width:1000px) {
  .home-container {
    width: 1200px;
    height: 430px;
  }
}

@media screen and (min-width:1000px) {
  .home-container {
    width: 1200px;
    height: 650px;
  }
}

.home {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.home-container {
  background: #FFFFFF;
  display: flex;
  position: relative;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.home-menu {
  width: 60px;
  background-color: #F7F7F7;
  border-right: 1px solid #eeeeee;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.shop-avatar {
  width: 50px;
  height: 50px;
  border-radius: 10px;
}

.menu-header {
  position: relative;
  margin: 20px auto;
  cursor: pointer;
}

.menu-header:hover .team-info {
  display: block;
  text-decoration: none;
}

.team-info {
  display: none;
  position: absolute;
  bottom: -20px;
  left: 0;
  right: 0;
  z-index: 1;
  width: 100px;
  padding: 0 8px;
  border: 0.5px solid rgba(108, 90, 90, 0.15);
  border-radius: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.5);
}

.menu-box {
  padding: 40px 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

.menu-list {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.menu-list .iconfont {
  padding: 15px;
  font-size: 28px;
  color: #606266;
}

.menu-item {
  color: #303133;
  cursor: pointer;
  height: 56px;
  position: relative;
}

.menu-unread {
  position: absolute;
  top: -5px;
  right: 5px;
  width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  border-radius: 50%;
  background-color: #fa5151;
  color: #ffffff;
}

.router-link-active i {
  color: #d02129 !important;
}

.agent-info:hover .agent-name {
  visibility: visible;
  text-decoration: none;
}

.agent-info {
  position: relative;
}

.agent-avatar {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  position: relative;
  cursor: pointer;
}

.agent-info .spot {
  position: absolute;
  left: 34px;
  top: 34px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.agent-info .online {
  background-color: #56d547;
}

.agent-info .offline {
  background-color: #999999;
}

.agent-name {
  visibility: hidden;
  position: absolute;
  top: 32px;
  bottom: 0;
  left: 32px;
  right: 0;
  border: 0.5px solid rgba(108, 90, 90, 0.15);
  border-radius: 4px;
  width: fit-content;
  max-width: 120px;
  height: 24px;
  line-height: 24px;
  padding: 0 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-wrap: break-word;
  background: #fff;
  color: rgba(0, 0, 0, 0.5);
  font-size: 12px;
  font-weight: 400;
  transition: all 0.4s 0.4s;
}

.action-wrap {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2;
}

.action-box {
  position: absolute;
  left: 60px;
  bottom: 40px;
  width: 150px;
  padding: 10px;
  background: #fff;
  border-radius: 10px;
  font-size: 14px;
  z-index: 3;
  box-shadow: 2px 8px 20px #999999;
}

.action-item {
  display: flex;
  flex-direction: column;
}

.action-item:hover {
  cursor: pointer;
}

.action-title {
  margin: 5px 0;
}

.action-detail {
  color: #5c5a5a;
  font-size: 12px;
  padding: 5px 0;
  border-bottom: 1px solid #efeeee;
}

.action-item .checked {
  margin: 5px 0;
  background: url("../assets/images/tick.png") no-repeat center center;
  background-size: 15px;
}

.home-main {
  padding: 0;
  flex: 1;
}
</style>
